const PkManageModule = require('../models/private_key_manage');
const AElfModule = require('../models/aelf');
const HistoryModule = require('../models/history')

exports.form = (req, res) => {
    const acct = req.query.acct;
    res.render('personal_page', { title: '个人主页', acct: acct });
};

exports.balance = (req, res) => {
    const aelf = new AElfModule();
    const data = req.query;

    console.log(data.acct);

    PkManageModule.get_priKey_by_user(data.acct, (user) => {
        aelf.check_chain_state((state) => {
            if (state) {
                aelf.load_wallet(user.priKey, (wallet) => {
                    if(typeof(wallet) !== 'undefined'){
                        aelf.load_contract(false , (param) =>{
                            console.log("contract prepared");
                            aelf.getBalance(param, function (result) {
                                res.send(result.balance);
                            });
                        });
                    }
                });
            }
        })
    });
}

exports.copyright = (req, res) => {
    const aelf = new AElfModule();
    const data = req.query;

    console.log(data.acct);

    PkManageModule.get_priKey_by_user(data.acct, (user) => {
        aelf.check_chain_state((state) => {
            if (state) {
                aelf.load_wallet(user.priKey, (wallet) => {
                    if(typeof(wallet) !== 'undefined'){
                        aelf.load_contract(true , (param) =>{
                            aelf.getAllCRTs(param, function (result) {
                                res.send(result);
                            });
                        });
                    }
                });
            }
        })
    });
}

exports.history = (req, res) => {
    const data = req.query;
    const log = new HistoryModule(data.acct);
    
    console.log(data.acct);

    log.GetHistory((ret)=>{
        res.send(ret);
    })
}